using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using ShopPowerTemplate.Entities;
using ShopPowerTemplate.IoC;
using ShopPowerTemplate.Presentation.Mvc.Extensions;
using ShopPowerTemplate.Presentation.Mvc.Models;
using ShopPowerTemplate.Presentation.Mvc.ViewModels;
using ShopPowerTemplate.Services;

namespace ShopPowerTemplate.Presentation.Mvc.Controllers
{
	public partial class OptionControllerBase : BaseController
	{
		#region Members

        protected IOptionService _optionService;
        protected IOptionTypeService _optionTypeService;
        protected IProductDetailService _productDetailService;

        #endregion

        #region Constructors

        public OptionControllerBase(IOptionService optionService, IOptionTypeService optionTypeService, IProductDetailService productDetailService)
        {
            _optionService = optionService;
            _optionTypeService = optionTypeService;
            _productDetailService = productDetailService;
        }	

        #endregion

		#region Index

		// **************************************
        // URL: /Option
        // **************************************
		public virtual ActionResult Index()
		{
			IndexOptionViewModel viewModel = new IndexOptionViewModel();
			ViewBag.PageIndex = this.GetPageIndex();
            ViewBag.PageSize = this.GetPageSize();
			ViewBag.SearchValue = this.GetSearchValue();
		
			return View(viewModel);
		}

		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult Load(string sidx, string sord, int page, int rows, string search, int mode = 1)
        {
            string searchValue = this.GetSearchValue();
            OrderBy orderBy = this.GetOrderBy();
            int pageIndex = this.GetPageIndex();
            int pageSize = this.GetPageSize();

            if (mode == (int)JQGridActionEnum.DefaultLoad)
            {                
                pageSize = (pageIndex + 1) * pageSize;
                pageIndex = 0;
            }
            else if (mode == (int)JQGridActionEnum.ShowMoreResults)
            {
                pageIndex = page;
                this.SetPageIndex(pageIndex);
            }
            else if (mode == (int)JQGridActionEnum.CustomSearch)
            {
                searchValue = search;
                this.SetSearchValue(searchValue);
                pageIndex = 0;
                this.SetPageIndex(pageIndex);
                orderBy = new OrderBy("", true);
                this.SetOrderBy(orderBy);
            }

            if (!string.IsNullOrEmpty(sidx)) // Sort request
            {
                orderBy = new OrderBy(sidx, sord == "asc");
                this.SetOrderBy(orderBy);
            }

            List<Option> searchList = _optionService.Search(searchValue, orderBy.Property, orderBy.Ascending, pageIndex, pageSize);
            int count = _optionService.SearchCount(searchValue);
            
			if (!string.IsNullOrEmpty(sidx)) // Sort request
            {
                pageIndex = this.GetPageIndex();
            }

            var data = new
            {
                total = Math.Ceiling((float)count/(float)pageSize),        // Total pages
                page = pageIndex,      // Current page
                records = count,  // Total records
                rows = from option in searchList     // Row data
                       select new
                       {
                           id = option.Id,                
                           cell = new string[] {
						   
                                option.Name,
								option.Description,
								option.OptionType != null ? option.OptionType.IdentityDescription : string.Empty
								
                           }
                       }
            };

            return Json(data);
        }

		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult Delete(int id)
        {
            try
            {
                _optionService.Remove(id);
            }
            catch (RemoveException ex)
            {
                Response.StatusCode = 500;
                return Content(ex.Message);
            }
            return Content(string.Empty);
        }
		
		public virtual FileContentResult Report()
        {
            IList<Option> _optionList = _optionService.Search(this.GetSearchValue());            
            StringBuilder strBuilder = new StringBuilder();

            // columns
            strBuilder.AppendLine("Name;Description;OptionType");

            // rows
            foreach (Option option in _optionList)
            {
                List<string> rowData = new List<string>() { option.Name, option.Description, option.OptionType != null ? option.OptionType.IdentityDescription : string.Empty };
                strBuilder.AppendLine(rowData.Aggregate((x, y) => x + ";" + y));
            }

			// encode report content
            System.IO.MemoryStream content = new System.IO.MemoryStream();
            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(content, UTF8Encoding.UTF8))
                writer.Write(strBuilder.ToString());

            return File(content.ToArray(), "text/csv", "Option.csv");
        }
		

		#endregion

		#region Create

		// *******************************************
        // URL: /Option/Create
        // *******************************************
		[AcceptVerbs(HttpVerbs.Get)]
        public virtual ActionResult Create()
        {
            Option option = new Option();
            CreateOptionViewModel viewModel = Mapper.Map<Option, CreateOptionViewModel>(option);
            List<OptionType> allOptionType = _optionTypeService.FindAll();
            viewModel.OptionTypeList = allOptionType;
            
			return View(viewModel);
        }

		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult Create(CreateOptionViewModel optionModel)
        {
            if (ModelState.IsValid)
            {
                Option option = new Option();
                AutoMapper.Mapper.Map<CreateOptionViewModel, Option>(optionModel, option);
 

				_optionService.Add(option);

                return RedirectToAction("Edit", new { id = option.Id});
            }
            else
            {
				List<OptionType> allOptionType = _optionTypeService.FindAll();
				optionModel.OptionTypeList = allOptionType;

                return View(optionModel);
            }
		}
		

		#endregion

		#region Edit

		// *******************************************
        // URL: /Option/Edit/id
        // *******************************************
		[AcceptVerbs(HttpVerbs.Get)]
        public virtual ActionResult Edit(int id)
        {
            Option option = _optionService.Find(id);
            EditOptionViewModel viewModel = Mapper.Map<Option, EditOptionViewModel>(option);
            List<OptionType> allOptionType = _optionTypeService.FindAll();
            viewModel.OptionTypeList = allOptionType;
				this.SetSearchValue("ProductDetailsSearchValue", "");
				this.SetOrderBy("ProductDetailsOrderBy", new OrderBy("", true));
				this.SetPageIndex("ProductDetailsPageIndex", 0);
				this.SetPageSize("ProductDetailsPageSize", 10);				
            
			return View(viewModel);
        }

		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult Edit(EditOptionViewModel optionModel)
        {
            if (ModelState.IsValid)
            {
                Option option = _optionService.Find(optionModel.Id);
                AutoMapper.Mapper.Map<EditOptionViewModel, Option>(optionModel, option);
                
				_optionService.Change(option);

                return RedirectToAction("Index");
            }
            else
            {
				List<OptionType> allOptionType = _optionTypeService.FindAll();
				optionModel.OptionTypeList = allOptionType;

                return View(optionModel);
            }
		}
		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult LoadSelectedProductDetails(string sidx, string sord, int page, int rows, string search, int mode = 1, int masterId = 0)
        {
			Option currentOption = _optionService.Find(masterId);
            List<ProductDetail> list = currentOption.ProductDetails.ToList();
			int count = list.Count();

			var data = new
            {
                total = 1,        // Total pages
                page = 1,      // Current page
                records = count,  // Total records
                rows = from productDetail in list     // Row data
                       select new
                       {
                           id = productDetail.Id,                
                           cell = new string[] {
                                productDetail.Stock.ToString(),
								productDetail.Product != null ? productDetail.Product.IdentityDescription : string.Empty
                           }
                       }
            };

            // Return elements
            return Json(data);
        }

		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult LoadAvailablesProductDetails(string sidx, string sord, int page, int rows, string search, int mode = 1, int masterId = 0)
        {
			string searchValue = this.GetSearchValue("ProductDetailsSearchValue");
            OrderBy orderBy = this.GetOrderBy("ProductDetailsOrderBy");
            int pageIndex = this.GetPageIndex("ProductDetailsPageIndex");
            int pageSize = this.GetPageSize("ProductDetailsPageSize");

            if (mode == (int)JQGridActionEnum.DefaultLoad)
            {
                pageSize = (pageIndex + 1) * pageSize;
                pageIndex = 0;
            }
            else if (mode == (int)JQGridActionEnum.ShowMoreResults)
            {
                pageIndex = page;
                this.SetPageIndex("ProductDetailsPageIndex", pageIndex);
            }
            else if (mode == (int)JQGridActionEnum.CustomSearch)
            {
                searchValue = search;
                this.SetSearchValue("ProductDetailsSearchValue", searchValue);
                pageIndex = 0;
                this.SetPageIndex("ProductDetailsPageIndex", pageIndex);
                orderBy = new OrderBy("", true);
                this.SetOrderBy("ProductDetailsOrderBy", orderBy);
            }

            Option currentOption = _optionService.Find(masterId);
            List<ProductDetail> searchList = _productDetailService.FindAvailableProductDetailList(currentOption.ProductDetails.ToList(), search, x => x.Id, true, pageIndex, pageSize);
            int count = _productDetailService.FindAvailableProductDetailListCount(currentOption.ProductDetails.ToList(), search);

            var data = new
            {
                total = Math.Ceiling((float)count / (float)pageSize),        // Total pages
                page = pageIndex,      // Current page
                records = count,  // Total records
                rows = from productDetail in searchList     // Row data
                       select new
                       {
                           id = productDetail.Id,
                           cell = new string[] {
                                productDetail.Stock.ToString(),
								productDetail.Product != null ? productDetail.Product.IdentityDescription : string.Empty
                           }
                       }
            };

            return Json(data);
        }

		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult AddProductDetails(int[] ids, int masterId = 0)
        {
			if(ids != null)
			{
				Option currentOption = _optionService.Find(masterId);

				foreach (int id in ids)
				{
					ProductDetail addProductDetail = _productDetailService.Find(id);
					_optionService.AddProductDetails(currentOption, addProductDetail);
				}
			}
			
			Response.StatusCode = 200;
			return Content("200", "text/plain");
		}

		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult RemoveProductDetails(int id, int masterId)
        {
			Option currentOption = _optionService.Find(masterId);
            ProductDetail removeProductDetail = _productDetailService.Find(id);
            _optionService.RemoveProductDetails(currentOption, removeProductDetail);

			Response.StatusCode = 200;
			return Content("200", "text/plain");
		}
		
		public virtual FileContentResult ReportProductDetails(int masterId = 0)
        {
			Option currentOption = _optionService.Find(masterId);
            IList<ProductDetail> _productDetailsList = currentOption.ProductDetails.ToList();          
            StringBuilder strBuilder = new StringBuilder();

            // columns
            strBuilder.AppendLine("Stock;Product");

            // rows
            foreach (ProductDetail productDetail in _productDetailsList)
            {
                List<string> rowData = new List<string>() { productDetail.Stock.ToString(), productDetail.Product != null ? productDetail.Product.IdentityDescription : string.Empty };
                strBuilder.AppendLine(rowData.Aggregate((x, y) => x + ";" + y));
            }

			// encode report content
            System.IO.MemoryStream content = new System.IO.MemoryStream();
            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(content, UTF8Encoding.UTF8))
                writer.Write(strBuilder.ToString());

            return File(content.ToArray(), "text/csv", "ProductDetails.csv");
        }
		

		#endregion

		#region Details

		// *******************************************
        // URL: /Option/Details/id
        // *******************************************
		[AcceptVerbs(HttpVerbs.Get)]
        public virtual ActionResult Details(int id)
        {
            Option option = _optionService.Find(id);
            DetailsOptionViewModel viewModel = Mapper.Map<Option, DetailsOptionViewModel>(option);
            
			return View(viewModel);
        }
		

		#endregion
	}
}
